package com.tanhua.dubbo.server.interceptor;

import com.tanhua.common.pojo.Admin;
import com.tanhua.common.pojo.User;
import com.tanhua.common.utils.AdminThreadLocal;
import com.tanhua.common.utils.NoAuthorization;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.dubbo.server.service.AdminService;
import com.tanhua.dubbo.server.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created with IntelliJ IDEA.
 *
 * @ClassName: UserTokenInterceptor
 * @Author:王晨晗
 * @Description: token令牌拦截器
 * @Date: 2021/12/30/11:09
 */
@Component
public class AdminTokenInterceptor implements HandlerInterceptor {

    @Autowired
    private AdminService adminService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //校验handler是否是handlerMethod
        if (!(handler instanceof HandlerMethod)){
            return true;
        }

        //判断是否包含指定注解(即不需要校验的请求进行放行)
        if (((HandlerMethod)handler).hasMethodAnnotation(NoAuthorization.class)){
            return true;
        }

        //从请求头中获取token
        String token = request.getHeader("Authorization");
        if (StringUtils.isNotEmpty(token)){
            Admin admin = adminService.queryToken(token);
            if (admin != null){
                //token有效存入ThreadLocal中
                AdminThreadLocal.set(admin);
                return true;
            }
        }

        //token无效,响应401
        response.setStatus(401);
        return false;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
    }
}
